<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? $t('page.system.role.edit') : $t('page.system.role.add')"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item
        :label="$t('page.system.role.name')"
        prop="name"
      >
        <el-input
          v-model="form.name"
          :placeholder="$t('page.system.role.form.nameRequired')"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.role.roleKey')"
        prop="roleKey"
      >
        <el-input
          v-model="form.roleKey"
          :placeholder="$t('page.system.role.form.roleKeyRequired')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item
        :label="$t('page.system.role.status')"
        prop="status"
      >
        <el-radio-group v-model="form.status">
          <el-radio :label="0">{{ $t('page.system.role.normal') }}</el-radio>
          <el-radio :label="1">{{ $t('page.system.role.disabled') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('page.system.role.cancel') }}
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ $t('page.system.role.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRadio,
  ElRadioGroup,
} from 'element-plus';

import type { RoleFormData } from '#/api/system/role';
import { createRoleApi, updateRoleApi } from '#/api/system/role';
import { $t } from '#/locales';

interface Props {
  visible: boolean;
  formData: Partial<RoleFormData>;
  isEdit: boolean;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const form = reactive<RoleFormData>({
  name: '',
  roleKey: '',
  status: 0,
});

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: $t('page.system.role.form.nameRequired'), trigger: 'blur' },
    { min: 2, max: 20, message: $t('page.system.role.form.nameLength'), trigger: 'blur' },
  ],
  roleKey: [
    { required: true, message: $t('page.system.role.form.roleKeyRequired'), trigger: 'blur' },
    { 
      pattern: /^[A-Z0-9_]+$/, 
      message: $t('page.system.role.form.roleKeyPattern'), 
      trigger: 'blur' 
    },
  ],
  status: [
    { required: true, message: $t('page.system.role.form.statusRequired'), trigger: 'change' },
  ],
};

// 监听 formData 变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(form, {
        id: newData.id,
        name: newData.name || '',
        roleKey: newData.roleKey || '',
        status: newData.status ?? 0,
      });
    }
  },
  { immediate: true, deep: true }
);

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    loading.value = true;
    
    if (props.isEdit) {
      await updateRoleApi(form);
      ElMessage.success($t('page.system.role.message.updateSuccess'));
    } else {
      await createRoleApi(form);
      ElMessage.success($t('page.system.role.message.createSuccess'));
    }
    
    emit('submit');
    handleClose();
  } catch (error) {
    console.error('提交表单失败:', error);
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  formRef.value?.resetFields();
  dialogVisible.value = false;
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style> 
 